package com.example.articleservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.articleservice.entity.Article;
import com.example.articleservice.entity.ArticleCategory;
import com.example.articleservice.entity.ArticleVo;
import com.example.articleservice.entity.Category;
import com.example.articleservice.service.*;
import com.example.common.Ajaxresult;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

import static java.lang.System.currentTimeMillis;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-02-19
 */
@RestController
@RequestMapping("/art")
public class ArticleController {
    @Autowired
    private IArticleService iArticleService;
    @Autowired
    private IArticleCategoryService iArticleCategoryService;
    @Autowired
    private IUserservice iUserservice;
    @Autowired
    private ICategoryService iCategoryService;
    @Autowired
    private  ICommentservice iCommentservice;
    @Value("${page.pagesize}")
    private Integer pagesize;
    @RequestMapping("/add")
    @Transactional
    public Ajaxresult add(ArticleVo articleVo,@RequestHeader(name="uid",required = false)Long uid) {
        if(articleVo==null||!StringUtils.hasLength(articleVo.getTitle())||
                !StringUtils.hasLength(articleVo.getContent())||articleVo.getCid()==null||articleVo.getCid()<=0||
        uid==null||uid<=0){
            return Ajaxresult.fail(-1,"参数有误");
        }
        articleVo.setUid(uid);
        //将文章持久化到文章表
        boolean result=iArticleService.save(articleVo);
        if(result){
            //将新增文章id和cid放到文章目录关联表当中
            ArticleCategory articleCategory=new ArticleCategory();
            articleCategory.setCid(articleVo.getCid());
            articleCategory.setAid(articleVo.getAid());
            boolean result2=iArticleCategoryService.save(articleCategory);
            return Ajaxresult.success(result2);
        }
        return Ajaxresult.fail(-1,"未知错误");

    }
    @RequestMapping("/getbyid")
    public Ajaxresult getbyid(Long aid){
        if(aid==null||aid<=0){
            return Ajaxresult.fail(-1,"参数有误");
        }
        //根据aid查文章
       Article article= iArticleService.getById(aid);
        if(article==null||article.getAid()<=0){
            return Ajaxresult.fail(-1,"数据库没有此文章");
        }
        //根据aid查文章d对应的目录分类
        QueryWrapper<ArticleCategory>categoryQueryWrapper=new QueryWrapper<>();
        categoryQueryWrapper.eq("aid",aid);
        ArticleCategory articleCategory=iArticleCategoryService.getOne(categoryQueryWrapper);
        ArticleVo articleVo=new ArticleVo();
        if(articleCategory!=null){
            Category category=iCategoryService.getById(articleCategory.getCid());
            articleVo.setAid(article.getAid());
            articleVo.setTitle(article.getTitle());
            articleVo.setContent(article.getContent());
            articleVo.setCid(articleCategory.getCid());
            articleVo.setUsername(iUserservice.getusername(article.getUid()));
            articleVo.setUid(article.getUid());
            articleVo.setCategory(category.getName());
            return Ajaxresult.success(articleVo);
        }
        return Ajaxresult.fail(-1,"未查询到此文章");
    }
    @Transactional
    @RequestMapping("/update")
    public Ajaxresult update(ArticleVo articleVo,@RequestHeader(name="uid",required = false)Long uid){
        if(articleVo==null||!StringUtils.hasLength(articleVo.getTitle())||
                !StringUtils.hasLength(articleVo.getContent())||articleVo.getCid()==null||articleVo.getCid()<=0||
                uid==null||uid<=0){
            return Ajaxresult.fail(-1,"参数有误");
        }
        //修改文章
        UpdateWrapper<Article>updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("uid",uid);
        updateWrapper.eq("aid",articleVo.getAid());
        LocalDateTime updatetime = LocalDateTime.ofInstant(Instant.ofEpochMilli(currentTimeMillis()), ZoneId.systemDefault());
        articleVo.setUpdatetime(updatetime);
        boolean result=iArticleService.update(articleVo,updateWrapper);
        if(!result){
            return Ajaxresult.fail(-1,"参数有误");
        }
        QueryWrapper<ArticleCategory>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("aid",articleVo.getAid());
        ArticleCategory articleCategory2=iArticleCategoryService.getOne(queryWrapper);
        if(articleCategory2!=null&&articleCategory2.getAcid()>0){
            //文章修改成功，删除文章修改前对应的文章分类表里的数据
            boolean result2=iArticleCategoryService.removeById(articleCategory2.getAcid());
        }
        //将新的文章分类信息放入数据库
        ArticleCategory articleCategory=new ArticleCategory();
        articleCategory.setAid(articleVo.getAid());
        articleCategory.setCid(articleVo.getCid());
        boolean result3=iArticleCategoryService.save(articleCategory);
        if(result3){
            return Ajaxresult.success(result3);
        }
        return Ajaxresult.fail(-1,"参数有误");
    }
    @RequestMapping("/getuserart")
    public Ajaxresult getuserart(Integer uid){
          if(uid==null||uid<=0){
              return Ajaxresult.fail(-1,"参数有误");
          }
          QueryWrapper<Article>queryWrapper=new QueryWrapper<>();
          queryWrapper.eq("uid",uid);
          //将查询出来的文章按文章aid降序排序
          queryWrapper.orderByDesc("aid");
        List<Article>articleList=iArticleService.list(queryWrapper);
        return Ajaxresult.success(articleList);

    }
    @GlobalTransactional
    @RequestMapping("/delbyaid")
    public Ajaxresult delbyaid(Integer aid,@RequestHeader(value="uid",required = false)Long uid){
        if(aid==null||aid<=0||uid==null||uid<=0){
            return Ajaxresult.fail(-1,"未知错误");
        }
        QueryWrapper<Article>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("aid",aid);
        //文章必须是自己的才能删除
        queryWrapper.eq("uid",uid);
          boolean result=iArticleService.remove(queryWrapper);
          //删除文章后，删除文章对应的评论
          boolean result2=iCommentservice.delcomentbyaid(aid);
          if(!result){
              return Ajaxresult.fail(-1,"参数错误");
          }
          return Ajaxresult.success(true);
    }
    @RequestMapping("/getlistbypage")
    public Ajaxresult getlistbypage(Integer pIndex){
        Page page=new Page(pIndex,pagesize);
        QueryWrapper<Article>articleQueryWrapper=new QueryWrapper<>();
        //拿取得数据按文章id降序排序
        articleQueryWrapper.orderByDesc("aid");
        Page<Article>result=iArticleService.page(page,articleQueryWrapper);
        return Ajaxresult.success(result);
    }
    @RequestMapping("/getuidbyaid")
    public Long getuidbyaid(Long aid){
        Article article=iArticleService.getById(aid);
        if(article==null||article.getAid()<=0){
            return 0l;
        }
        return article.getUid();
    }



}
